package com.yunshu.yunshuapp.zixunlist;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunshu.yunshuapp.ImageActivity;
import com.yunshu.yunshuapp.NavigationBar;
import com.yunshu.yunshuapp.OnTapListener;
import com.yunshu.yunshuapp.R;
import com.yunshu.yunshuapp.WebviewActivity;
import com.yunshu.yunshuapp.banner.BannerClass;
import com.yunshu.yunshuapp.banner.ScrollBanner;
import com.yunshu.yunshuapp.network.YSCallback;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.utils.YSUtils;
import com.yunshu.yunshuapp.views.SegmentControlView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

public class ZixunListActivity extends AppCompatActivity {

    private static final int MSG_RECYLEVIEW_UPDATE = 100;
    /**
     * ZixunListModel.List_ID_HANGYEYAOWEN
     */
    private String listType = ZixunListModel.List_ID_CHANGSHANGJIAGE;
    private int pageIndex = 0;
    private RecyclerView mRecyclerView;
    private String[] ads;
    private ArrayList<ZixunListModel> models;
    private com.yunshu.yunshuapp.zixunlist.ZixunListAdapter adapter;
    private YSRequest request;
    private SwipeRefreshLayout swipeRefreshLayout;
    private Handler mExtHandler;
//    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        NavigationBar bar = (NavigationBar) findViewById(R.id.navigationBar);
        bar.setTitle("资讯");
        bar.putInActivity(this);
        request = new YSRequest(this);

        this.addSegement();

        this.addList();

        this.requestBanner();
        this.refresh();
        this.initListener();
        mExtHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_RECYLEVIEW_UPDATE:
                        adapter.setModels(models);
                        adapter.notifyDataSetChanged();
                        break;
                }
                super.handleMessage(msg);
            }
        };
    }

    private void refresh() {
        pageIndex = 1;
        request.GET(YSRequest.ZIXUN_LIST, "type=" + listType +"&page=1", new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                endRefreshing();
                if (isSuccess != YSRequest.REQUEST_OK) return;
                if (!result.isArray()) return;
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<ZixunListModel> temp = new ArrayList<ZixunListModel>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        ZixunListModel model = mapper.readValue(jsonstr, ZixunListModel.class);
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                models = temp;
                pageIndex +=1;
                reloadData();
            }
        });
    }

    private void loadmore() {
        request.GET(YSRequest.ZIXUN_LIST, "type=" + listType +"&page="+pageIndex, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                endRefreshing();
                if (isSuccess != YSRequest.REQUEST_OK) return;
                if (!result.isArray()) return;
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<ZixunListModel> temp = new ArrayList<ZixunListModel>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        ZixunListModel model = mapper.readValue(jsonstr, ZixunListModel.class);
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                pageIndex +=1;
                models.addAll( temp);
                reloadData();
            }
        });
    }

    private void endRefreshing() {
        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(false);
            }
        });


    }

    private void requestBanner(){
        request.GET(YSRequest.ZIXUN_Banner, null, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                if (isSuccess != YSRequest.REQUEST_OK || !result.isArray()){
                    showBanner(null);
                    return;
                }
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<BannerClass> temp = new ArrayList<BannerClass>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        BannerClass model = mapper.readValue(jsonstr, BannerClass.class);
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                showBanner(temp);
            }

        });
    }

    private void showBanner(final ArrayList<BannerClass> temp) {

        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                if(temp == null || temp.size() == 0){
                    return;
                }
                ScrollBanner bannerView = getBanner();
                ArrayList<String> imgUrls = new ArrayList<String>();
                for (BannerClass banner : temp){
                    imgUrls.add(banner.getImgUrl());
                }
                ads =  imgUrls.toArray(new String[]{});
                bannerView.setImages(ads);
                adapter.setBanner(bannerView);
            }
        });

    }

    private void reloadData() {
//        runOnUiThread(new Runnable() {      // UI thread
//            @Override
//            public void run() {
//                adapter.models = models;
//                adapter.notifyDataSetChanged();
//            }
//        });
        Message msg;
        msg = Message.obtain();
        msg.what = MSG_RECYLEVIEW_UPDATE;
        mExtHandler.sendMessage(msg);

    }

    private void addList() {
        mRecyclerView = (RecyclerView) findViewById(R.id.list_view);
        // use a linear layout manager
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        //设置RecycleView的显示方向：（默认为垂直） 水平
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);

        adapter = new com.yunshu.yunshuapp.zixunlist.ZixunListAdapter(getBaseContext());
        adapter.activity = com.yunshu.yunshuapp.zixunlist.ZixunListActivity.this;
        mRecyclerView.setAdapter(adapter);

        swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_container);
        //设置刷新时动画的颜色，可以设置4个
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                refresh();
            }
        });
    }


    private void addSegement() {
        SegmentControlView segement = (SegmentControlView) findViewById(R.id.scv);
//        View title = findViewById(R.id.title);
//        Bundle bundle = this.getIntent().getExtras();

//        if(bundle == null || bundle.get("listtype") == null){
//            segement.setVisibility(View.VISIBLE);
//            title.setVisibility(View.INVISIBLE);
//        }else{
//            listType = (String) bundle.get("listtype");
//            segement.setVisibility(View.INVISIBLE);
//            title.setVisibility(View.VISIBLE);
//        }

        segement.setOnSegmentChangedListener(new SegmentControlView.OnSegmentChangedListener() {
            @Override
            public void onSegmentChanged(int newSelectedIndex) {
                changeListType(newSelectedIndex);
            }
        });
        //set viewpager to change segment according to the state of viewpager
        //set the selected index of segments initiatively
        segement.setSelectedIndex(0);
        //set gradient effect if you want
        segement.setGradient(true);
    }

    private void changeListType(int newSelectedIndex) {
        switch (newSelectedIndex){
            case 0:
                listType = ZixunListModel.List_ID_CHANGSHANGJIAGE;
                break;
            case 1:
//                listType = ZixunListModel.List_ID_SHICHANGHANGQING;
//                break;
//            case 2:
                listType = ZixunListModel.List_ID_REDIANZIXUN;
                break;
//            case 3:
//                listType = ZixunListModel.List_ID_SHICHANGGUANCHA;
//                break;
        }

        this.refresh();
    }


    private ScrollBanner getBanner() {
        int screenWidth = YSUtils.screenWidth(this); // 获取屏幕宽度
        final ScrollBanner banner = new ScrollBanner(this);
        ViewGroup.LayoutParams layout = new ViewGroup.LayoutParams(screenWidth, (int) (screenWidth*0.43));
//        layout.width = screenWidth;
//        layout.height = (int) (screenWidth*0.43);
        banner.setLayoutParams(layout);

        banner.bannerClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int index = banner.indexOfView(v);
                Intent intent = new Intent();
                intent.setClass(com.yunshu.yunshuapp.zixunlist.ZixunListActivity.this, ImageActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("imgUrl",ads[index]);
                intent.putExtras(bundle);
                startActivityForResult(intent,0);
//                MainActivity.this.finish();
            }
        };
        return banner;
    }

    private void initListener() {

//        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                onBackPressed();
//            }
//        });

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem ;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                //判断RecyclerView的状态 是空闲时，同时，是最后一个可见的ITEM时才加载
                if(newState==RecyclerView.SCROLL_STATE_IDLE&&lastVisibleItem+1==adapter.getItemCount()){

                    loadmore();


                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem=layoutManager.findLastVisibleItemPosition();
            }
        });

    }
}
